using System;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace XCZProject
{
	public partial class CameraController : ViewController
	{
		private static CameraController mDefault = null;

		public static Transform LBTrans => mDefault.LB;
		public static Transform RTTrans => mDefault.RT;
		
		private Vector2 mTargetPosition=Vector2.zero;

		private Vector3 mCurrentCameraPos;
		private bool mShake = false;
		private int mShakeFrame = 0;
		private float mShakeA = 4.0f;// 振幅

		private void Awake()
		{
			mDefault = this;
		}

		private void Start()
		{
			//Application.targetFrameRate = 120;// 游戏锁定60帧
		}

		private void OnDestroy()
		{
			mDefault = null;
		}

		private void Update()
		{
			if (Player.Default)
			{
				mTargetPosition = Player.Default.transform.position;
				// 摄像机x轴平滑跟随
				mCurrentCameraPos.x=(
					(1.0f - Mathf.Exp(-Time.deltaTime * 5))
						.Lerp(transform.position.x, mTargetPosition.x));
				// 摄像机y轴平滑跟随
				mCurrentCameraPos.y=(
					(1.0f - Mathf.Exp(-Time.deltaTime * 5))
						.Lerp(transform.position.y, mTargetPosition.y));

				mCurrentCameraPos.z = transform.position.z;
				//mCurrentCameraPos = transform.position;

				if (mShake)
				{
					mShakeFrame--;
					// 当mshake为true的时候才进行震屏
					var shakeA = Mathf.Lerp(mShakeA, 0.0f, (mShakeFrame / 30.0f));
				
					transform.position = new Vector3(mCurrentCameraPos.x + Random.Range(-shakeA, shakeA),
						mCurrentCameraPos.y + Random.Range(-shakeA, shakeA),mCurrentCameraPos.z);
				
					if (mShakeFrame<=0)
					{
						mShake = false;
					}
				}
				else
				{
					// 摄像机x轴平滑跟随
					transform.PositionX(
						(1.0f - Mathf.Exp(-Time.deltaTime * 5))
						.Lerp(transform.position.x, mTargetPosition.x));
					// 摄像机y轴平滑跟随
					transform.PositionY(
						(1.0f - Mathf.Exp(-Time.deltaTime * 5))
						.Lerp(transform.position.y, mTargetPosition.y));
				}
				
			}
		}

		public static void Shake()
		{
			mDefault.mShake = true;
			mDefault.mShakeFrame = 30;
			mDefault.mShakeA = 0.1f;
		}
	}
}
